<template>
  <div class="app-container">
    <el-row>
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :inline="true" v-show="showSearch" label-width="140px" :label-position="isPhone ? 'top' : 'left'">
          <el-form-item label="姓名" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入姓名"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="学校" prop="trainUniversity">
            <el-select
              v-model="queryParams.trainUniversity"
              placeholder="请选择学校"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="item in university"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="专业" prop="trainMajor">
            <el-input
              v-model="queryParams.trainMajor"
              placeholder="请输入专业"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="入企实践开始时间" prop="practiceStartYear">
            <el-select
              v-model="queryParams.practiceStartYear"
              placeholder="请选择年份"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="year in yearOptions"
                :key="year"
                :label="year + '年'"
                :value="year"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasRole="['admin', 'student']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="handleGetList"
            :columns="columns"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="list"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="姓名"
            align="center"
            key="nickName"
            prop="nickName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
            width="100"
          />
          <el-table-column
            label="学校"
            align="center"
            key="trainUniversity"
            prop="trainUniversity"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
            width="150"
          >
            <template #default="scope">
              {{ getUniversityText(scope.row.trainUniversity) }}
            </template>
          </el-table-column>
          <el-table-column
            label="专业"
            align="center"
            key="trainMajor"
            prop="trainMajor"
            v-if="columns[3].visible"
            :show-overflow-tooltip="true"
            width="150"
          />
          <el-table-column
            label="培养单位"
            align="center"
            key="trainDeptName"
            prop="trainDeptName"
            v-if="columns[4].visible"
            :show-overflow-tooltip="true"
            width="150"
          />
          <el-table-column
            label="入企时间"
            align="center"
            key="joinEntStartDate"
            prop="joinEntStartDate"
            v-if="columns[5].visible"
            :show-overflow-tooltip="true"
            width="150"
          />
          <el-table-column
            label="课题名称"
            align="center"
            key="joinEntTopicName"
            prop="joinEntTopicName"
            v-if="columns[6].visible"
            :show-overflow-tooltip="true"
            width="200"
          />
          <el-table-column
            label="课题简介"
            align="center"
            key="joinEntTopicIntroduction"
            prop="joinEntTopicIntroduction"
            v-if="columns[7].visible"
            :show-overflow-tooltip="true"
            width="250"
          />
          <el-table-column
            label="论文开题计划时间"
            align="center"
            key="thesisStartTime"
            prop="thesisStartTime"
            v-if="columns[8].visible"
            width="140"
          />
          <el-table-column
            label="中期考核计划时间"
            align="center"
            key="thesisMidTime"
            prop="thesisMidTime"
            v-if="columns[9].visible"
            width="140"
          />
          <el-table-column
            label="论文预答辩计划时间"
            align="center"
            key="thesisPreTime"
            prop="thesisPreTime"
            v-if="columns[10].visible"
            width="140"
          />
          <el-table-column
            label="论文答辩计划时间"
            align="center"
            key="thesisEndTime"
            prop="thesisEndTime"
            v-if="columns[11].visible"
            width="140"
          />
          <el-table-column
            label="操作"
            align="center"
            width="150"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-tooltip content="详情" placement="top">
                <el-button
                  link
                  type="info"
                  icon="View"
                  @click="handleDetail(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip :content="scope.row.approvalStatus === 'approved' ? '草稿' : '修改'" placement="top">
                <el-button
                  link
                  type="primary"
                  :icon="scope.row.approvalStatus === 'approved' ? 'Document' : 'Edit'"
                  @click="handleUpdate(scope.row)"
                  v-hasRole="['admin', 'student']"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-if="scope.row.approvalStatus !== 'approved'"
                  v-hasRole="['admin', 'student']"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                content="提交"
                placement="top"
                v-if="
                  scope.row.approvalStatus === 'no_submit' ||
                  scope.row.approvalStatus === 'rejected'
                "
              >
                <el-button
                  link
                  type="warning"
                  icon="Upload"
                  @click="handleSubmit(scope.row)"
                  v-hasRole="['admin', 'student']"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                content="审批"
                placement="top"
                v-if="scope.row.approvalAuth"
              >
                <el-button
                  link
                  type="success"
                  icon="Check"
                  @click="handleApprove(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleGetList"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="EnterprisePracticeProgram">
import {
  getList,
  delItem,
} from "@/api/enterprise-practice-program";
import { submitApproval } from "@/api/approval";
import { isPhone } from "@/utils/index";
import { yearOptions } from "@/utils/constant";
import { useRouter } from 'vue-router'

const router = useRouter();
const { proxy } = getCurrentInstance();
const { university } = proxy.useDict("university");

const list = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 列显隐信息
const columns = ref([
  { key: 0, label: `编号`, visible: true },
  { key: 1, label: `姓名`, visible: true },
  { key: 2, label: `学校`, visible: true },
  { key: 3, label: `专业`, visible: true },
  { key: 4, label: `培养单位`, visible: true },
  { key: 5, label: `入企时间`, visible: true },
  { key: 6, label: `课题名称`, visible: true },
  { key: 7, label: `课题简介`, visible: true },
  { key: 8, label: `论文开题计划时间`, visible: true },
  { key: 9, label: `中期考核计划时间`, visible: true },
  { key: 10, label: `论文预答辩计划时间`, visible: true },
  { key: 11, label: `论文答辩计划时间`, visible: true },
]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nickName: undefined,
    trainUniversity: undefined,
    trainMajor: undefined,
    practiceStartYear: undefined,
  },
});

const { queryParams } = toRefs(data);

const userList = ref([]);

// 按钮loading状态
const submitLoading = ref(false);
const approvePassLoading = ref(false);
const approveRejectLoading = ref(false);
const planSubmitLoading = ref(false);

// 计划编辑对话框相关数据
const planDialogVisible = ref(false);
const planDialogTitle = ref("");
const planEditIndex = ref(-1); // 编辑的计划索引，-1表示新增
const planForm = ref({
  planName: "",
  planMonth: "",
  planStartTime: "",
  planEndTime: "",
  planTarget: "",
});

// 计划表单验证规则
const planRules = {
  planName: [
    { required: true, message: "请输入计划名称", trigger: "blur" }
  ],
  planMonth: [
    { required: true, message: "请选择计划月份", trigger: "change" }
  ],
  planStartTime: [
    { required: true, message: "请选择开始时间", trigger: "change" }
  ],
  planEndTime: [
    { required: true, message: "请选择结束时间", trigger: "change" }
  ],
  planTarget: [
    { required: true, message: "请输入实践目标", trigger: "blur" }
  ],
};

const formUserInfo = computed(() =>
  userList.value.find((t) => t.userId === form.value.userId)
);

/** 查询用户列表 */
function handleGetList() {
  loading.value = true;
  getList(queryParams.value).then((res) => {
    loading.value = false;
    list.value = res.rows;
    total.value = res.total;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  handleGetList();
}
function resetQuery() {
  queryParams.value.nickName = undefined;
  queryParams.value.trainUniversity = undefined;
  queryParams.value.trainMajor = undefined;
  queryParams.value.practiceStartYear = undefined;
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除编号为"' + id + '"的数据项？')
    .then(function () {
      return delItem(id);
    })
    .then(() => {
      handleGetList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/user/export",
    {
      ...queryParams.value,
    },
    `user_${new Date().getTime()}.xlsx`
  );
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  router.push({
    path: '/enterprise-practice-program/edit/new',
    query: { mode: 'add' }
  });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  const id = row.id || ids.value;
  router.push({
    path: `/enterprise-practice-program/edit/${id}`,
    query: { mode: 'edit' }
  });
}

// 提交审核
function handleSubmit(row) {
  const id = row.id || ids.value;
  const item = list.value.find(item => item.id === id);
  proxy.$modal
    .confirm("是否确认提交审核？")
    .then(function () {
      return submitApproval({
        businessId: id,
        approvalTypeCode: "ent_plan_flow",
        approvalInfo: JSON.stringify(item)
      });
    })
    .then(() => {
      handleGetList();
      proxy.$modal.msgSuccess("提交成功");
    })
    .catch(() => {});
}

// 审批操作
function handleApprove(row) {
  const id = row.id || ids.value;
  router.push({
    path: `/enterprise-practice-program/edit/${id}`,
    query: { mode: 'approve' }
  });
}

// 高校名称文本显示函数
const getUniversityText = (universityValue) => {
  if (!universityValue) return "未知";
  const dict = university.value?.find((item) => item.value === universityValue);
  return dict ? dict.label : universityValue;
};

handleGetList();

/** 详情操作 */
function handleDetail(row) {
  const id = row.id || ids.value;
  router.push({
    path: `/enterprise-practice-program/edit/${id}`,
    query: { mode: 'detail' }
  });
}
</script>

<style scoped>
.text-overflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 200px;
}
</style>